// 禁止选中文字
document.addEventListener('selectstart', function (e) {
    e.preventDefault();
})
/*顶部下拉出现隐藏顶部*/
window.addEventListener("scroll", function () {
    let Top = document.querySelector(".detailList").offsetTop;
    if (document.documentElement.scrollTop >= Top) {
        document.querySelector(".headerHidden").style.top = "0px";
        document.querySelector(".headerHidden").style.transition = 'all .3s'
    } else {
        document.querySelector(".headerHidden").style.top = "-80px";
        document.querySelector(".headerHidden").style.transition = 'none'
    }
});
// 放大镜功能
let img = document.querySelector('.middle img')
let large = document.querySelector('.large')
let layer = document.querySelector(".layer")
let middle = document.querySelector('.middle')
let picture = document.querySelector('.picture')
document.querySelector('.small').addEventListener('mouseover', e => {
    if (e.target.tagName === 'IMG') {
        document.querySelector('li.active').classList.remove("active")
        e.target.parentNode.classList.add('active')
        img.src = e.target.src
        large.style.backgroundImage = `url(${e.target.src})`
    }
})
middle.addEventListener("mouseenter", () => {
    large.style.display = 'block'
    layer.style.display = 'block'
})
middle.addEventListener("mouseleave", () => {
    large.style.display = 'none'
    layer.style.display = 'none'
})
middle.addEventListener('mousemove', e => {
    let x = e.pageX - picture.offsetLeft - layer.offsetWidth / 2
    let y = e.pageY - picture.offsetTop - layer.offsetHeight / 2
    if (x < 0) { x = 0 }
    if (x > middle.offsetWidth - layer.offsetWidth) { x = middle.offsetWidth - layer.offsetWidth }
    if (y < 0) { y = 0 }
    if (y > middle.offsetHeight - layer.offsetHeight) { y = middle.offsetHeight - layer.offsetHeight }
    layer.style.left = x + 'px'
    layer.style.top = y + 'px'
    large.style.backgroundPositionX = -2 * x + 'px'
    large.style.backgroundPositionY = -2 * y + 'px'
})
selectAddress()
// 配送地址筛选 封装函数
function selectAddress() {
    // 定义数组对象
    let addressData =
        [
            {
                id: 1,
                province: '北京',
                city: [
                    { id: 1, name: '北京市', district: ['东城区', '西城区', '崇文区', '宣武区', '朝阳区', '丰台区', '石景山区', '海淀区', '门头沟区', '房山区', '通州区', '顺义区', '昌平区', '大兴区', '怀柔区', '平谷区', '密云区', '延庆区', '经济技术开发区'] },
                ],
            },
            {
                id: 2,
                province: '陕西省',
                city: [
                    { id: 1, name: '西安市', district: ['新城区', '碑林区', '莲湖区', '灞桥区', '未央区', '阎良区', '临潼区', '长安区', '高陵区', '鄠邑区', '蓝田县', '周至县'] },
                    { id: 1, name: '铜川市', district: ['王益区', '印台区', '耀州区', '宜君县'] },
                    { id: 1, name: '宝鸡市', district: ['渭滨区', '岐山县', '千阳县', '金台区', '扶风县', '麟游县', '陈仓区', '眉县', '凤县', '凤翔县', '陇县', '太白县'] },
                    { id: 1, name: '咸阳市', district: ['秦都区', '泾阳县', '彬县', '武功县', '杨陵区', '乾县', '长武县', '兴平市', '渭城区', '礼泉县', '旬邑县', '二原县', '永寿县', '淳化县'] },
                    { id: 1, name: '渭南市', district: ['临渭区', '合阳县', '富平县', '华县', '澄城县', '潼关县', '蒲城县', '大荔县', '白水县', '韩城市', '华阴市'] },
                    { id: 1, name: '延安市', district: ['宝塔区', '子长县', '富县', '安塞区', '志丹县', '洛川县', '延长县', '吴起县', '宜川县', '延川县', '甘泉县', '黄龙县', '黄陵县'] },
                    { id: 1, name: '汉中市', district: ['汉台区', '西乡县', '镇巴县', '南郑县', '勉县', '留坝县', '城固县', '宁强县', '佛坪县', '洋县', '略阳县'] },
                    { id: 1, name: '榆林市', district: ['榆阳区', '靖边县', '佳县', '神木市', '定边县', '吴堡县', '府谷县', '绥德县', '清涧县', '横山县', '米脂县', '子洲县'] },
                    { id: 1, name: '安康市', district: ['汉滨区', '紫召加', '旬阳县', '汉阴县', '岚皋县', '白河县', '石泉县', '平利县', '宁陕县', '镇坪县'] },
                    { id: 1, name: '商洛市', district: ['商州区', '山阳县', '洛南县', '镇安县', '丹凤县', '柞水县', '商南县'] },
                ],
            }
        ]
    let specGoods = document.querySelector('.specGoods')
    let sp = document.querySelector('.select span')
    // 定义初始值
    sp.innerHTML = '北京市 市辖区 东城区'
    specGoods.addEventListener('click', function (e) {
        // 后面代码监听了body 所以阻止冒泡
        e.stopPropagation()
        // 如有多出来的option框 将其删除
        if (specGoods.querySelector('.option')) {
            this.removeChild(specGoods.querySelector('.option'))
        }
        let div = document.createElement('div')
        div.classList.add("option")
        let str = ''
        // div.innerHTML = `<span>陕西省</span>`
        str = addressData.map(item => {
            const { id, province, city } = item
            return `<span>${province}</span>`
        }).join('')
        div.innerHTML = str
        // console.log(str);
        let str1 = ''
        for (let i = 0; i < addressData.length; i++) {
            if (e.target.innerHTML === addressData[i].province) {
                // 点击省份 存入本地
                localStorage.setItem('temp', e.target.innerHTML)
                for (let j = 0; j < addressData[i].city.length; j++) {
                    str1 += `<span>${addressData[i].city[j].name}</span>`
                }
                div.innerHTML = str1
            }
        }
        let str2 = ''
        for (let i = 0; i < addressData.length; i++) {
            for (let j = 0; j < addressData[i].city.length; j++) {
                if (e.target.innerHTML === addressData[i].city[j].name) {
                    // 点击城市 存入本地
                    localStorage.setItem('temp1', e.target.innerHTML)
                    // temp1 = addressData[i].city[j].name
                    for (let k = 0; k < addressData[i].city[j].district.length; k++) {
                        str2 += `<span>${addressData[i].city[j].district[k]}</span>`
                    }
                    div.innerHTML = str2
                }
            }
        }
        this.appendChild(div)
        for (let i = 0; i < addressData.length; i++) {
            for (let j = 0; j < addressData[i].city.length; j++) {
                for (let k = 0; k < addressData[i].city[j].district.length; k++) {
                    if (e.target.innerHTML === addressData[i].city[j].district[k]) {
                        // 点击区县 存入本地
                        localStorage.setItem('temp2', e.target.innerHTML)
                        let div = specGoods.querySelector('.option')
                        // 删除option框
                        if (div) {
                            this.removeChild(div)
                        }
                        // 获取本地数据
                        let temp = localStorage.getItem('temp')
                        let temp1 = localStorage.getItem('temp1')
                        let temp2 = localStorage.getItem('temp2')
                        sp.innerHTML = temp + ' ' + temp1 + ' ' + temp2
                    }
                }
            }
        }
    })
    // 点击除配送框以外的区域时，取消option区域显示
    document.body.addEventListener('click', function () {
        let div = specGoods.querySelector('.option')
        if (div) {
            specGoods.removeChild(div)
        }
    })
}
let imgs = document.querySelectorAll('.specSkus ul li:nth-child(2) img')
let spans = document.querySelectorAll('.specSkus ul:nth-child(2) li:nth-child(2) span')
// tab栏切换功能
document.querySelector('.specSkus').addEventListener('click', e => {
    if (e.target.tagName === 'SPAN') {
        if (e.target.classList.contains('selected')) {
            e.target.classList.toggle('selected')
        } else {
            for (let i = 0; i < spans.length; i++) {
                spans[i].classList.remove('selected')
            }
            e.target.classList.toggle('selected')
        }
    }
    if (e.target.tagName === 'IMG') {
        if (e.target.classList.contains('selected')) {
            e.target.classList.remove('selected')
        } else {
            for (let i = 0; i < imgs.length; i++) {
                imgs[i].classList.remove('selected')
            }
            e.target.classList.add('selected')
        }
    }
})
// 增加减少数量功能
let add = document.querySelector("#add")
let reduce = document.querySelector("#reduce")
let input = document.querySelector(".specNumber .numbox>input")
add.addEventListener('click', () => {
    input.value++
})
reduce.addEventListener('click', () => {
    input.value--
    if (input.value < 1) {
        input.value = 1
    }
})
// 加入购物车功能
let specBtn = document.querySelector('.specBtn')
let messWrong = document.querySelector('.message .messWrong')
let message = document.querySelector('.message')
let messRight = document.querySelector('.message .messRight')
function color() {
    let imgs = document.querySelectorAll('.specSkus ul li:nth-child(2) img')
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].classList.contains('selected')) {
            return true
        }
    }
    return false
}
function size() {
    let spans = document.querySelectorAll('.specSkus ul:nth-child(2) li:nth-child(2) span')
    for (let i = 0; i < spans.length; i++) {
        if (spans[i].classList.contains('selected')) {
            return true
        }
    }
    return false
}

let space1 = ''
let space2 = ''
let skuObj = {}
document.querySelector('.spec').addEventListener('click', function (e) {
    if (e.target.tagName === 'IMG') {
        space1 = `颜色:${e.target.title}`
        pic = e.target.src
    }
    if (e.target.tagName === 'SPAN') {
        space2 = `尺码:${e.target.innerHTML}`
    }
    if (!input.value) {
        input.value = 1
    }
    skuObj = {
        name: document.querySelector('.spec').children[0].innerHTML,
        count: input.value,
        price: document.querySelector('.spec').children[2].children[0].innerHTML,
        picture: pic,
        attrsText: space1 + ' ' + space2
    }
})
let flag = true
let timer = null
specBtn.addEventListener('click', () => {
    if (color() && size()) {
        if (flag) {
            flag = false
            messRight.style.display = 'block'
            messWrong.style.display = 'none'
            message.style.top = '25px'
            message.style.zIndex = 9999
            goodsList2.push(skuObj)
            localStorage.setItem('data', JSON.stringify(goodsList2))
            carRender(goodsList2)
            input.value = 1
            clearTimeout(timer)
            timer = setTimeout(() => {
                messRight.style.display = 'none'
                message.style.top = '0'
                message.style.zIndex = -200
                flag = true
            }, 1500)
        }
    } else {
        if (flag) {
            flag = false
            messWrong.style.display = 'block'
            messRight.style.display = 'none'
            message.style.top = '25px'
            message.style.zIndex = 9999
            clearTimeout(timer)
            timer = setInterval(() => {
                messWrong.style.display = 'none'
                message.style.top = '0'
                message.style.zIndex = -200
                flag = true
            }, 1500)
        }
    }
})
const goodsList2 = [
    {
        id: "4001874",
        skuId: "300294887",
        name: "古法温酒汝瓷酒具套装白酒杯莲花温酒器",
        attrsText: "规格:珍藏套组（1壶4杯1托盘）+温酒器 ",
        specs: [],
        picture:
            "https://yanxuan-item.nosdn.127.net/44e51622800e4fceb6bee8e616da85fd.png",
        price: "1888.00",
        nowPrice: "1888.00",
        nowOriginalPrice: "1888.00",
        selected: true,
        stock: 2579,
        count: 1,
        isEffective: true,
        discount: null,
        isCollect: false,
        postFee: 2.0,
    },
    {
        id: "4003488",
        skuId: "300306318",
        name: "全防水HABU旋钮牛皮户外徒步鞋山宁泰抗菌",
        attrsText: "颜色:骑士黑 尺码:39 ",
        specs: [],
        picture:
            "https://yanxuan-item.nosdn.127.net/221317c85274a188174352474b859d7b.jpg",
        price: "444.00",
        nowPrice: "444.00",
        nowOriginalPrice: "444.00",
        selected: true,
        stock: 7670,
        count: 1,
        isEffective: true,
        discount: null,
        isCollect: false,
        postFee: 2.0,
    },
    {
        id: "4004350",
        skuId: "300311908",
        name: "网易味央黑猪大排330g*1袋",
        attrsText: "规格:大排330g*1袋 ",
        specs: [],
        picture:
            "https://yanxuan-item.nosdn.127.net/a078d2c4b8559b0a54430a0dc6460095.jpg",
        price: "37.00",
        nowPrice: "37.00",
        nowOriginalPrice: "37.00",
        selected: true,
        stock: 3222,
        count: 2,
        isEffective: true,
        discount: null,
        isCollect: false,
        postFee: 7.0,
    },
];
function carRender(arr) {
    num = 0;
    const htmlStr = arr.reduce(function (prev, item) {
        return (
            prev +
            `<div class="item">
      <a>
          <img src="${item.picture}"
              alt="">
          <div class="carCenter">
              <p>${item.name}</p>
              <p>${item.attrsText}</p>
          </div>
          <div class="carRight">
              <p>${item.price}</p>
              <p>x${item.count}</p>
          </div>
      </a>
      <i class="delite" data-index=${num++}>×</i>
  </div>`
        );
    }, "");
    document.querySelector(".carList").innerHTML = htmlStr;
    document.querySelector(".car span").innerHTML = `${goodsList2.length}`;
    document.querySelector(
        ".carTotal p:nth-child(1)"
    ).innerHTML = `共 ${goodsList2.length} 件商品`;
    let couse = goodsList2.map(function (item) {
        return +item.price;
    });
    let i = 0;
    for (let num = 0; num < couse.length; num++) {
        i += +couse[num];
    }
    document.querySelector(".carTotal p:nth-child(2)").innerHTML = `¥${i}`;
}

carRender(goodsList2);
//购物车删除功能
let dels = document.querySelectorAll(".carList i");
carList.addEventListener("mouseover", function (e) {
    if (e.target.className === "item") {
        for (let i = 0; i < dels.length; i++) {
            dels[i].style.opacity = 0;
        }
        e.target.children[1].style.opacity = 1;
    }
});
carList.addEventListener('click', function (e) {
    if (e.target.className === 'delite') {
        goodsList2.splice(e.target.dataset.index, 1)
        // localStorage.setItem('indexdata', JSON.stringify(goodsList))
        carRender(goodsList2);
    }
})
// 同类商品推荐
let roundDate = {
    "msg": "操作成功",
    "result": {
        "counts": 304, "pageSize": 20, "pages": 16, "page": 1,
        "items":
            [
                { "id": "3995195", "name": "毛茸茸暖意，儿童羊羔绒外套73-120cm", "desc": "宽松版型，搭出休闲风格", "price": "99.00", "picture": "https://yanxuan-item.nosdn.127.net/1661541f80bc9776e64125b7d586c9e6.jpg", "discount": null, "orderNum": 356 },
                { "id": "3997565", "name": "可机洗系列-女式尖头平底鞋", "desc": "解放双手，随盒赠送洗鞋袋", "price": "179.00", "picture": "https://yanxuan-item.nosdn.127.net/f5c2bd141d6640123532410bea6aecc2.png", "discount": null, "orderNum": 233 },
                { "id": "3989765", "name": "宜兴原矿紫砂壶茶具礼盒5件套", "desc": "纯正紫砂原矿料，百年经典器型", "price": "599.00", "picture": "https://yanxuan-item.nosdn.127.net/cec3c630e88787200095a8e11ee9942f.png", "discount": null, "orderNum": 167 },
                { "id": "3987192", "name": "PC膜拉链拉杆箱系列（17/20/24/28寸）", "desc": "磨砂高级质地，轻巧短途出行", "price": "206.00", "picture": "https://yanxuan-item.nosdn.127.net/8e1ee389d18a90fa00f338dc8534587a.png", "discount": null, "orderNum": 556 },
                { "id": "1418015", "name": "告别油腻解放双手，懒人抹布超值囤货装16卷", "desc": "16卷800节，用完即扔，洗碗打扫不脏手", "price": "176.00", "picture": "https://yanxuan-item.nosdn.127.net/52a8dfbbce131f621ef6d9d02476ed91.png", "discount": null, "orderNum": 151 },
                { "id": "1622006", "name": "网易智造冷暖轻薄汽车坐垫", "desc": "高速静音双风机设计|冷暖两用", "price": "249.00", "picture": "https://yanxuan-item.nosdn.127.net/e4cf5dc8a43d9d1336f4579ab8a72d70.png", "discount": null, "orderNum": 458 },
                { "id": "1622019", "name": "电动红酒开瓶器锂电池快充", "desc": "风靡美国，6S开瓶", "price": "129.00", "picture": "https://yanxuan-item.nosdn.127.net/4bfd44beec46454f55fd35f4dd8ae262.png", "discount": null, "orderNum": 233 },
                { "id": "3398019", "name": "祛味猫砂伴侣396克", "desc": "细腻粉末深入猫砂，强力祛味", "price": "49.00", "picture": "https://yanxuan-item.nosdn.127.net/95cb93ddb067b498327c9b7338a0af70.jpg", "discount": null, "orderNum": 268 },
                { "id": "3804045", "name": "男式经典切尔西商务正装鞋", "desc": "商务新经典，出众的脚感体验", "price": "444.00", "picture": "https://yanxuan-item.nosdn.127.net/94f800da40ffaf2633e1338a2cfbf54e.png", "discount": null, "orderNum": 156 },
                { "id": "3827035", "name": "拥有整个星空俄罗斯设计弦月流星项链", "desc": "一款项链九种戴法，浪漫星月设计", "price": "149.00", "picture": "https://yanxuan-item.nosdn.127.net/95d2b3d442b7208a5123164e1ff6c052.png", "discount": null, "orderNum": 156 },
                { "id": "1435014", "name": "原汁原味根根酥脆泰国香脆椰子卷16g*12", "desc": "泰国新鲜椰汁制作，根根酥脆", "price": "29.00", "picture": "https://yanxuan-item.nosdn.127.net/90cd2aeb3208a28c51a76111cd40e2d3.png", "discount": null, "orderNum": 190 },
                { "id": "3995192", "name": "毛茸茸小熊出没，儿童羊羔绒背心73-90cm", "desc": "连帽熊耳设计，萌化少女心", "price": "79.00", "picture": "https://yanxuan-item.nosdn.127.net/cd4b840751ef4f7505c85004f0bebcb5.png", "discount": null, "orderNum": 144 },
                { "id": "3997532", "name": "“柿柿”如意，新年夹棉连体衣/棉服0-5岁", "desc": "三层锁温舒适，仿丝绵加倍保暖", "price": "159.00", "picture": "https://yanxuan-item.nosdn.127.net/3cb61b3fd4761555e56c4a5f19d1b4b1.png", "discount": null, "orderNum": 121 },
                { "id": "1524002", "name": "多功能环保除臭猫砂盆雾灰色", "desc": "封闭抽屉式设计，隔臭易清理", "price": "179.00", "picture": "https://yanxuan-item.nosdn.127.net/8f1ca43da72e151c66455310a143a77d.jpg", "discount": null, "orderNum": 151 },
                { "id": "1451027", "name": "净水花洒好搭档韩国花洒替换滤芯2只装", "desc": "适配除氯花洒，效果肉眼可见", "price": "49.00", "picture": "https://yanxuan-item.nosdn.127.net/eba436352816180993555d11fff87087.png", "discount": null, "orderNum": 84 },
                { "id": "3994896", "name": "冬季不怕冷，婴童加厚保暖爬服", "desc": "宝宝冬天不再冷，保暖常备单品", "price": "139.00", "picture": "https://yanxuan-item.nosdn.127.net/7170d6147878a099914b7bb7ce21773f.png", "discount": null, "orderNum": 292 }]
    }
}
let arr = roundDate.result.items
// 封装渲染函数
function render() {
    let ul = document.querySelector(".core ul")
    let start = 0
    let end = 4
    for (let i = 0; i < 4; i++) {
        let str = ''
        let li = document.createElement('li')
        let div = document.createElement("div")
        for (let j = start; j < end; j++) {
            str += `<a>
      <img src=${arr[j].picture} alt="">
       <p>${arr[j].name}</p>
       <p>¥${arr[j].price}</p>
        </a>`
        }
        start += 4
        end += 4
        div.innerHTML = str
        li.appendChild(div)
        ul.appendChild(li)
        ul.children[0].classList.add('fade')
    }

}
render()
// 按钮切换
let next = document.querySelector('.next')
let prev = document.querySelector('.prev')
let lis = document.querySelectorAll('.core ul li')
let spans1 = document.querySelectorAll('.indicator span')
let ic = 0
next.addEventListener('click', () => {
    ic++
    if (ic > lis.length - 1) {
        ic = 0
    }
    common()
})
prev.addEventListener('click', () => {
    ic--
    if (ic < 0) {
        ic = lis.length - 1
    }
    common()
})
document.querySelector('.indicator').addEventListener('click', e => {
    if (e.target.tagName === 'SPAN') {
        ic = e.target.id
        common()
    }
})
function common() {
    document.querySelector('.core li.fade').classList.remove("fade")
    lis[ic].classList.add('fade')
    document.querySelector('.indicator span.active').classList.remove("active")
    spans1[ic].classList.add('active')
}
//商品评价tab栏切换
let ul = document.querySelector('.tabs ul')
let divs = document.querySelectorAll('.tabs>div')
ul.addEventListener('click', e => {
    if (e.target.tagName === 'LI') {
        document.querySelector('.tabs li.active').classList.remove('active')
        e.target.classList.add('active')
        for (let i = 0; i < divs.length; i++) {
            divs[i].style.display = 'none'
        }
        divs[e.target.id].style.display = 'block'
    }
})
let tags = document.querySelector('.tags ul')
tags.addEventListener('click', e => {
    if (e.target.tagName === 'LI') {
        tags.querySelector('li.active').classList.remove('active')
        e.target.classList.add('active')
    }
})
// 评论渲染数组
let commentData = {
    "result":
    {
        "counts": 86, "page": "2", "pageSize": 10, "pages": 9,
        "items": [
            {
                "id": 11,
                "orderInfo": {
                    "specs": [
                        { "name": "颜色", "nameValue": "白色" },
                        { "name": "尺寸", "nameValue": "10cm" },
                        { "name": "产地", "nameValue": "美国" }],
                    "quantity": 1,
                    "createTime": "2020-10-10 19:20:20"
                },
                "member": { "id": "10021", "nickname": "兔子tony", "avatar": "http://zhoushugang.gitee.io/erabbit-client-pc-static/uploads/avatar_1.png" },
                "score": 5,
                "tags": ["速度快", "质量好"],
                "content": "锅好看，很重，拿锅的时候手最好不要有水，会滑。做菜时锅很烫要小心。锅边有一点瑕疵，锅内底部有一点凸起。锅内水不能超过2/3，否则即使小火也会溢水。总体还可以。",
                "pictures": [],
                "officialReply": "",
                "praiseCount": 118,
                "createTime": "2021-04-03 13:20:32"
            },
            { "id": 12, "orderInfo": { "specs": [{ "name": "颜色", "nameValue": "白色" }, { "name": "尺寸", "nameValue": "10cm" }, { "name": "产地", "nameValue": "美国" }], "quantity": 1, "createTime": "2020-10-10 19:20:20" }, "member": { "id": "10021", "nickname": "兔子tony", "avatar": "http://zhoushugang.gitee.io/erabbit-client-pc-static/uploads/avatar_1.png" }, "score": 5, "tags": ["速度快", "质量好"], "content": "很有分量！颜色太漂亮了很喜欢很喜欢！做工也算比较精细", "pictures": ["https://yanxuan.nosdn.127.net/0f19c7edf5b78f4e94503bf74bc425e7.jpg?type=webp&imageView&quality=95&thumbnail=603x438", "https://yanxuan.nosdn.127.net/6cb114f4b71ce2ca51eeea4cbf761a2a.jpg?type=webp&imageView&quality=95&thumbnail=603x438", "https://yanxuan.nosdn.127.net/9c894107bc2a1e56de2644e674dcdb7b.jpg?type=webp&imageView&quality=95&thumbnail=603x438", "https://yanxuan.nosdn.127.net/21789984b356ff2ca4c7b727d70c8636.jpg?type=webp&imageView&quality=95&thumbnail=603x438", "https://yanxuan.nosdn.127.net/aee32572782a2d5a1d9255f32d76ade8.jpg?type=webp&imageView&quality=95&thumbnail=603x438"], "officialReply": "", "praiseCount": 68, "createTime": "2021-04-03 13:20:32" },
            { "id": 13, "orderInfo": { "specs": [{ "name": "颜色", "nameValue": "白色" }, { "name": "尺寸", "nameValue": "10cm" }, { "name": "产地", "nameValue": "美国" }], "quantity": 1, "createTime": "2020-10-10 19:20:20" }, "member": { "id": "10021", "nickname": "兔子tony", "avatar": "http://zhoushugang.gitee.io/erabbit-client-pc-static/uploads/avatar_1.png" }, "score": 3, "tags": ["充电快", "音质好"], "content": "很有分量！颜色太漂亮了很喜欢很喜欢！做工也算比较精细", "pictures": [], "officialReply": "", "praiseCount": 117, "createTime": "2021-04-01 13:20:32" },
            { "id": 14, "orderInfo": { "specs": [{ "name": "颜色", "nameValue": "白色" }, { "name": "尺寸", "nameValue": "10cm" }, { "name": "产地", "nameValue": "美国" }], "quantity": 1, "createTime": "2020-10-10 19:20:20" }, "member": { "id": "10021", "nickname": "兔子tony", "avatar": "http://zhoushugang.gitee.io/erabbit-client-pc-static/uploads/avatar_1.png" }, "score": 5, "tags": ["速度快", "质量好"], "content": "這個煱我看中了3年，終於在大減價時下手。性價比超高！😁😁😁 今天剛剛收到，包裝精美，閃令令漂亮到冇朋友！😍😍😍 下星期會開煱！十分期待啊！", "pictures": [], "officialReply": "", "praiseCount": 155, "createTime": "2021-04-05 13:20:32" },
            { "id": 15, "orderInfo": { "specs": [{ "name": "颜色", "nameValue": "白色" }, { "name": "尺寸", "nameValue": "10cm" }, { "name": "产地", "nameValue": "美国" }], "quantity": 1, "createTime": "2020-10-10 19:20:20" }, "member": { "id": "10021", "nickname": "兔子tony", "avatar": "http://zhoushugang.gitee.io/erabbit-client-pc-static/uploads/avatar_1.png" }, "score": 3, "tags": ["充电快", "音质好"], "content": "锅好看，很重，拿锅的时候手最好不要有水，会滑。做菜时锅很烫要小心。锅边有一点瑕疵，锅内底部有一点凸起。锅内水不能超过2/3，否则即使小火也会溢水。总体还可以。", "pictures": [], "officialReply": "", "praiseCount": 1, "createTime": "2021-04-07 13:20:32" },
            { "id": 16, "orderInfo": { "specs": [{ "name": "颜色", "nameValue": "白色" }, { "name": "尺寸", "nameValue": "10cm" }, { "name": "产地", "nameValue": "美国" }], "quantity": 1, "createTime": "2020-10-10 19:20:20" }, "member": { "id": "10021", "nickname": "兔子tony", "avatar": "http://zhoushugang.gitee.io/erabbit-client-pc-static/uploads/avatar_1.png" }, "score": 5, "tags": ["充电快", "质量好"], "content": "锅好看，很重，拿锅的时候手最好不要有水，会滑。做菜时锅很烫要小心。锅边有一点瑕疵，锅内底部有一点凸起。锅内水不能超过2/3，否则即使小火也会溢水。总体还可以。", "pictures": ["https://yanxuan.nosdn.127.net/0f19c7edf5b78f4e94503bf74bc425e7.jpg?type=webp&imageView&quality=95&thumbnail=603x438", "https://yanxuan.nosdn.127.net/6cb114f4b71ce2ca51eeea4cbf761a2a.jpg?type=webp&imageView&quality=95&thumbnail=603x438", "https://yanxuan.nosdn.127.net/9c894107bc2a1e56de2644e674dcdb7b.jpg?type=webp&imageView&quality=95&thumbnail=603x438", "https://yanxuan.nosdn.127.net/21789984b356ff2ca4c7b727d70c8636.jpg?type=webp&imageView&quality=95&thumbnail=603x438", "https://yanxuan.nosdn.127.net/aee32572782a2d5a1d9255f32d76ade8.jpg?type=webp&imageView&quality=95&thumbnail=603x438"], "officialReply": "", "praiseCount": 110, "createTime": "2021-04-03 13:20:32" },
            { "id": 17, "orderInfo": { "specs": [{ "name": "颜色", "nameValue": "白色" }, { "name": "尺寸", "nameValue": "10cm" }, { "name": "产地", "nameValue": "美国" }], "quantity": 1, "createTime": "2020-10-10 19:20:20" }, "member": { "id": "10021", "nickname": "兔子tony", "avatar": "http://zhoushugang.gitee.io/erabbit-client-pc-static/uploads/avatar_1.png" }, "score": 5, "tags": ["速度快", "音质好"], "content": "颜色好看，很重，做工略次一点，但也对的起这个价格了", "pictures": [], "officialReply": "", "praiseCount": 58, "createTime": "2021-04-08 13:20:32" },
            { "id": 18, "orderInfo": { "specs": [{ "name": "颜色", "nameValue": "白色" }, { "name": "尺寸", "nameValue": "10cm" }, { "name": "产地", "nameValue": "美国" }], "quantity": 1, "createTime": "2020-10-10 19:20:20" }, "member": { "id": "10021", "nickname": "兔子tony", "avatar": "http://zhoushugang.gitee.io/erabbit-client-pc-static/uploads/avatar_1.png" }, "score": 4, "tags": ["速度快", "质量好"], "content": "這個煱我看中了3年，終於在大減價時下手。性價比超高！😁😁😁 今天剛剛收到，包裝精美，閃令令漂亮到冇朋友！😍😍😍 下星期會開煱！十分期待啊！", "pictures": [], "officialReply": "", "praiseCount": 36, "createTime": "2021-04-03 13:20:32" },
            { "id": 19, "orderInfo": { "specs": [{ "name": "颜色", "nameValue": "白色" }, { "name": "尺寸", "nameValue": "10cm" }, { "name": "产地", "nameValue": "美国" }], "quantity": 1, "createTime": "2020-10-10 19:20:20" }, "member": { "id": "10021", "nickname": "兔子tony", "avatar": "http://zhoushugang.gitee.io/erabbit-client-pc-static/uploads/avatar_1.png" }, "score": 3, "tags": ["充电快", "质量好"], "content": "昨天下单，今天中午开锅就试着烧了五花肉，耗时30分钟，一切都刚刚好，比以前的锅烧出来口感汤汁都好多了，且价格实惠！建议购买！", "pictures": [], "officialReply": "", "praiseCount": 20, "createTime": "2021-04-03 13:20:32" },
            { "id": 20, "orderInfo": { "specs": [{ "name": "颜色", "nameValue": "白色" }, { "name": "尺寸", "nameValue": "10cm" }, { "name": "产地", "nameValue": "美国" }], "quantity": 1, "createTime": "2020-10-10 19:20:20" }, "member": { "id": "10021", "nickname": "兔子tony", "avatar": "http://zhoushugang.gitee.io/erabbit-client-pc-static/uploads/avatar_1.png" }, "score": 4, "tags": ["速度快", "音质好"], "content": "這個煱我看中了3年，終於在大減價時下手。性價比超高！😁😁😁 今天剛剛收到，包裝精美，閃令令漂亮到冇朋友！😍😍😍 下星期會開煱！十分期待啊！", "pictures": [], "officialReply": "", "praiseCount": 137, "createTime": "2021-04-06 13:20:32" }]
    }
}
let arr1 = commentData.result.items
function commentRender(arr) {
    let j = 0
    document.querySelector(".detailFooter .list").innerHTML = arr.reduce((prev, item) => {
        j++
        const { score, content, createTime, praiseCount, pictures } = item
        // sku处理
        let spec = item.orderInfo.specs
        let specStr = ''
        for (let i = 0; i < spec.length; i++) {
            specStr += Object.values(spec[i]).join(':') + ' '
        }
        //星级处理
        let star = ''
        let empty = ''
        let light = ''
        if (score === 5) {
            for (let i = 0; i < 5; i++) {
                star += '<i class="iconfont icon-wujiaoxing-"></i>'
            }
        } else {
            let remain = 5 - score
            for (let i = 0; i < score; i++) {
                light += '<i class="iconfont icon-wujiaoxing-"></i>'
            }
            for (let i = 0; i < remain; i++) {
                empty += '<i class="iconfont icon-shoucang"></i>'
            }
            star = light + empty
        }
        // 图片预览处理
        let imageStr = ''
        let liStr = ''
        if (pictures.length === 0) {
            imageStr = ''
        } else {
            for (let i = 0; i < pictures.length; i++) {
                liStr += `<li><img src="${pictures[i]}" alt=""></li>`
            }
            imageStr = `<div class="image">
        <ul>
          ${liStr}
        </ul>
        <div class="preview">
          <img src="${pictures[0]}" alt="">
            <i class="el-icon-close"></i>
        </div>
      </div>`
        }
        return prev + `<div class="item">
       <div class="user">
           <img src="${item.member.avatar}"
               alt="">
           <span>${item.member.nickname}</span>
       </div>
       <div class="body">
           <div class="score">
               ${star}
               <span>${specStr}</span>
           </div>
           <div class="text">
               ${content}
           </div>
            ${imageStr}
           <div class="time">
               <span>${createTime}</span>
               <span id="prasize">
                   <i class="el-icon-thumb"></i>
                   <em id=${j}>${praiseCount}</em>
               </span>
           </div>
       </div>
   </div>`
    }, '')
}
commentRender(arr1)
// 排序
let sort = document.querySelector('.sort')
// 深拷贝
const arr2 = []
let arr3 = []
let arr4 = []
let arr5 = []
let arr6 = []
let arr7 = []
function deepCopy(newObj, oldObj) {
    for (let k in oldObj) {
        if (oldObj[k] instanceof Array) {
            let arr = []
            deepCopy(arr, oldObj[k])
            newObj[k] = arr
            // console.log(obj2[k]);
        } else if (oldObj[k] instanceof Object) {
            let obj = {}
            deepCopy(obj, oldObj[k])
            newObj[k] = obj
        } else {
            newObj[k] = oldObj[k]
        }
    }
}
deepCopy(arr2, arr1)
deepCopy(arr3, arr1)
deepCopy(arr7, arr1)
sort.addEventListener('click', function (e) {
    if (e.target.tagName === 'A') {
        this.querySelector('a.active').classList.remove('active')
        e.target.classList.add('active')
    }
    if (e.target.dataset.name === '0') {
        commentRender(arr1)
    }
    if (e.target.dataset.name === '1') {
        arr3.forEach(item => {
            let count = +new Date() - +new Date(item.createTime)
            item.timestamp = count
        })
        arr5 = arr3.sort((x, y) => {
            return x.timestamp - y.timestamp
        })
        commentRender(arr5)
    }
    if (e.target.dataset.name === '2') {
        arr4 = arr2.sort((x, y) => {
            return y.praiseCount - x.praiseCount
        })
        commentRender(arr4)
    }
})
document.querySelector('.tags').addEventListener('click', e => {
    if (e.target.dataset.say === '0') {
        commentRender(arr1)
    }
    if (e.target.dataset.say === '1') {
        arr6 = arr1.filter(item => item.pictures.length != 0)
        commentRender(arr6)
    }
    if (e.target.dataset.say === '2') {
        arr6 = arr1.filter(item => item.tags[1] === '音质好')
        commentRender(arr6)
    }
    if (e.target.dataset.say === '3') {
        arr6 = arr1.filter(item => item.tags[0] === '充电快')
        commentRender(arr6)
    }
    if (e.target.dataset.say === '4') {
        arr4 = arr2.sort((x, y) => {
            return y.praiseCount - x.praiseCount
        })
        commentRender(arr4)
    }
    if (e.target.dataset.say === '5') {
        arr6 = arr7.sort((x, y) => {
            return y.content.length - x.content.length
        })
        commentRender(arr6)
    }
})
// 图片预览功能实现
let list = document.querySelector('.list')
let lis1 = document.querySelectorAll('.image ul li')
let flag1 = true
list.addEventListener('click', e => {
    if (e.target.tagName === 'IMG') {
        let lis2 = e.target.parentNode.parentNode.children
        for (let i = 0; i < lis2.length; i++) {
            lis2[i].classList.remove('active')
        }
        let preview = e.target.parentNode.parentNode.nextElementSibling
        let previewImg = e.target.parentNode.parentNode.nextElementSibling.children[0]
        preview.style.display = 'block'
        previewImg.src = e.target.src
        e.target.parentNode.classList.add('active')
    }
    if (e.target.className === 'el-icon-close') {
        e.target.parentNode.style.display = 'none';
        let lis3 = e.target.parentNode.previousElementSibling.children
        for (let i = 0; i < lis3.length; i++) {
            lis3[i].classList.remove('active')
        }
    }
    // 点赞功能
    if (e.target.tagName === 'EM') {
        if (e.target.parentNode.classList.contains('active')) {
            e.target.parentNode.classList.remove('active')
            e.target.innerHTML--
            arr1[+e.target.id - 1].praiseCount = e.target.innerHTML
        } else {
            e.target.parentNode.classList.add('active')
            e.target.innerHTML++
            arr1[+e.target.id - 1].praiseCount = e.target.innerHTML
        }
    }
})
// 分页功能
function Pagination(obj) {
    this.init(obj)
}
Pagination.prototype = {
    pages: {
        pageCount: 0,//页面总数
        size: 10,//单页面数据量
        pageNo: 1//当前页
    },
    //初始化页面数据,参数:obj
    init: function (obj) {
        var pages = this.pages
        pages.total = obj.total//总数据量
        obj.pageCount = Math.ceil(obj.total / obj.size)//总页码数
        pages.container = obj.container//外部容器
        pages.pageNo = obj.pageNo//当前页
        pages.pageCount = obj.pageCount//总页码数
        pages.eleHtml = obj.eleHtml//标签内部值
        pages.prevPage = obj.prevPage || 'prevPage'//上一页按钮
        pages.nextPage = obj.nextPage || 'nextPage'//下一页按钮
        this.renderPage(pages)
    },
    //构建页面,参数:args
    renderPage(args) {
        var pageContainer = this.selectEle(args.container)
        var pageStr = '', start, end
        //构建左侧点击按钮
        if (args.pageNo > 1) {
            pageStr = `<a class="prevPage">上一页</a>`
        } else {
            pageStr = `<a class="disabled">上一页</a>`
        }
        //构建中间页面按钮区域
        if (args.pageCount < 6) {//当总页码数小于6时
            for (start = 0; start < args.pageCount; start++) {
                end = start + 1
                if (end == args.pageNo) {
                    pageStr += '<a class="active">' + end + '</a>'
                } else {
                    pageStr += '<a>' + end + '</a>'
                }
            }
        } else {//当总页码大于等于6时
            start = args.pageNo - 1//确认遍历的起始位置为当前页的前一页
            end = args.pageNo + 1//确认遍历的结束位置为当前页的后一页
            if (args.pageNo > 2) { pageStr += '<a>' + 1 + '</a>' }//当前页大于2时，将页面1按钮写死
            else { end = 4 }//当前页小于等于2时，将遍历的结束位置写死为4
            if (args.pageNo > args.pageCount - 3) { start = args.pageCount - 3 }//当前页为最后四个页面时，将遍历的起始位置写死为倒数第四个页面值
            if (args.pageNo > 3) { pageStr += '<a>...</a>' }//当前页大于第三个页面时，将省略号按钮展现出来
            //对中间按钮进行遍历
            for (; start <= end; start++) {
                if (start <= args.pageCount && start > 0) {
                    if (start == args.pageNo) {
                        pageStr += '<a class="active">' + start + '</a>'
                    } else {
                        pageStr += '<a>' + start + '</a>'
                    }
                }
            }
            if (args.pageNo < args.pageCount - 2) { pageStr += '<i>...</i>' }//当前页面小于倒数第三个页面时，将省略号按钮展现出来
            if (args.pageNo < args.pageCount - 1) { pageStr += '<a>' + args.pageCount + '</a>' }//当前页面小于倒数第二个页面，将最后的页面按钮锁死
        }
        //构建右侧按钮
        if (args.pageNo < args.pageCount) {
            pageStr += `<a class="nextPage">下一页</a>`
        } else {
            pageStr += `<a class="disabled">下一页</a>`
        }
        pageContainer.innerHTML = pageStr
        this.switchPage()
    },
    //切换页面
    switchPage() {
        let pages = this.pages, g = this
        let aList = this.selectEle(pages.container + " a", true)//获取所有的a标签
        let current//定义一个当前页的标识
        //对所有的a标签遍历，绑定点击事件
        for (i in aList) {
            if (i < aList.length) {
                aList[i].addEventListener("click", function () {
                    console.log(123);
                    let eleHtml = this.innerHTML//定义一个属性值来获取数字按钮
                    if (this.className == pages.prevPage) {
                        pages.pageNo > 1 && (pageNo = pages.pageNo - 1)
                    } else if (this.className == pages.nextPage) {
                        pages.pageNo < pages.pageCount && (pageNo = pages.pageNo + 1)
                    } else {
                        pageNo = parseInt(eleHtml)
                    }
                    pageNo && g.gotoPage(pageNo)
                })
            }
        }
    },
    //跳转页面,参数:current
    gotoPage(current) {
        this.pages.pageNo = current
        this.renderPage(this.pages)
    },
    //获取页面元素
    selectEle(select, all) {
        return all ? document.querySelectorAll(select) : document.querySelector(select)
    }
}
var p = new Pagination({
    container: '.pagination',
    size: 10,
    pageNo: 1,
    total: 100
})
